import 'dart:io';

import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:preview_family_bucket/preview_image/gallery_photo_preview_item.dart';

typedef ChoseDeleteImageCallbck = Future<bool> Function(String id);
typedef PageCurrentIndexCallback = void Function(int currentIndex);
typedef PageNumWidgetCallback = Positioned Function(int currentIndex);
class GalleryPhotoViewWrapper extends StatefulWidget {
  GalleryPhotoViewWrapper({
    // this.loadingBuilder,
    this.backgroundDecoration,
    this.minScale,
    this.maxScale,
    this.initialIndex,
    @required this.galleryItems,
    this.scrollDirection = Axis.horizontal,
    this.choseDeleteImageCallbck,
    this.isDeleteContainer,
    this.pageCurrentIndexCallback,
    this.logoWidget,
    this.backWidget,
    this.pageNumWidgetCallback
  }) : pageController = PageController(initialPage: initialIndex);

  // final LoadingBuilder loadingBuilder;
  final Decoration backgroundDecoration;
  final dynamic minScale;
  final dynamic maxScale;
  final int initialIndex;
  final PageController pageController;
  final List<GalleryPhotoPreviewItem> galleryItems;
  final Axis scrollDirection;
  final ChoseDeleteImageCallbck choseDeleteImageCallbck;
  final Widget isDeleteContainer;
  final Widget backWidget;
  final PageCurrentIndexCallback pageCurrentIndexCallback;///翻页时回调当前index
  final Positioned logoWidget;///图片上的logo
  PageNumWidgetCallback pageNumWidgetCallback;///翻页计数的widget

  @override
  State<StatefulWidget> createState() {
    return _GalleryPhotoViewWrapperState();
  }
}

class _GalleryPhotoViewWrapperState extends State<GalleryPhotoViewWrapper> {
  int currentIndex;

  @override
  void initState() {
    currentIndex = widget.initialIndex;
    super.initState();
  }

  void onPageChanged(int index) {
    setState(() {
      currentIndex = index;
    });
    if(widget.pageCurrentIndexCallback != null){
      widget.pageCurrentIndexCallback(index);
    }
  }

  @override
  Widget build(BuildContext context) {
    if(currentIndex >= widget.galleryItems.length){
      currentIndex = widget.galleryItems.length-1;
    }
    if(currentIndex<=0){
      currentIndex=0;
    }
    Positioned aawidget = widget.pageNumWidgetCallback(currentIndex);
    return Scaffold(
      body: Container(
          decoration: widget.backgroundDecoration,
          constraints: BoxConstraints.expand(
            height: MediaQuery.of(context).size.height,
          ),
          child: Stack(
            alignment: Alignment.topRight,
            children: <Widget>[
              PhotoViewGallery.builder(
                scrollPhysics: const BouncingScrollPhysics(),
                builder: _buildItem,
                itemCount: widget.galleryItems.length,
                // loadingBuilder: widget.loadingBuilder,
                backgroundDecoration: widget.backgroundDecoration,
                pageController: widget.pageController,
                onPageChanged: onPageChanged,
                scrollDirection: widget.scrollDirection,
                gaplessPlayback: true,
                enableRotation: true,
              ),
              Positioned(
                left:20,
                top: 20,
                child: InkWell(
                  onTap: (){
                    Navigator.of(context).pop();
                  },
                  child: widget.backWidget??Container(width:1, height:1),
                )
              ),
              aawidget ??
              Positioned(
                bottom:20,
                right: 20,
                child: Text(
                  "Image ${currentIndex + 1}",
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 17.0,
                    decoration: null,
                  ),
                ),),
              widget.logoWidget != null
              ? (widget.galleryItems[currentIndex].isShowLogo ? widget.logoWidget : Container(width:1,height: 1))
              :  Container(width:1,height: 1),
              widget.galleryItems[currentIndex].isCanDelete ?
              Positioned(
                top:20,
                right: 20,
                child: InkWell(
                  onTap: (){
                    Future<bool> isDelete =  widget.choseDeleteImageCallbck(widget.galleryItems[currentIndex].id);
                    isDelete.then((value){
                      if(value){
                        widget.galleryItems.removeAt(currentIndex);
                        if(widget.galleryItems.isEmpty){
                            Navigator.pop(context);
                        }else{
                          setState(() {
                          });
                        }
                        print('删除成功');
                      }else{
                        print('不删除');
                      }
                    });
                  },
                  child: widget.isDeleteContainer != null ? widget.isDeleteContainer : Container(
                      width: 50,
                      height: 30,
                      alignment: Alignment.center,
                      child: Text(
                        "删除",
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 12.0,
                          // decoration: null,
                        ),
                      ),
                    )
                )
              )
              :
              Container(width:1,height: 1),
            ],
          ),
        ),
    );
  }

  PhotoViewGalleryPageOptions _buildItem(BuildContext context, int index) {
    final GalleryPhotoPreviewItem item = widget.galleryItems[index];

    return PhotoViewGalleryPageOptions(//AssetImage(item.resource)
            imageProvider: item.url.length > 0 ? NetworkImage(item.url) : (item.resource.length > 0 ? AssetImage(item.resource,) : FileImage(item.file)),
            initialScale: PhotoViewComputedScale.contained,
            // minScale: PhotoViewComputedScale.contained * (0.5 + index / 10),
            maxScale: PhotoViewComputedScale.covered * 1.0,
            heroAttributes: PhotoViewHeroAttributes(tag: item.id),
            onTapUp: (context,detail,controller){
              Navigator.pop(context);
            },
          );
  }
}
